var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session= require('express-session');
var mongoStore=require("connect-mongo")(session);//注意
var flash=require("connect-flash");


var indexRouter = require('./routes/index');//路由
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));//render第一个参数去哪找模板
app.set('view engine', 'ejs');//名字

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());//中间件
app.use(express.static(path.join(__dirname, 'public')));//静态文件处理，比如没给配路由的css，都去public下找


//session中间件
app.use(session({
  secret:"xiangpichi",//hash的签名
  cookie:({ path: '/', httpOnly: true,secure: false, maxAge:  60000 }),
  resave:true,
  saveUninitialized:true,
  store: new mongoStore({
    url:"mongodb://localhost:27017/",
    dbName:"Users"
  })
}));
app.use(flash());//req.flash配置



app.use('/', indexRouter);//输入地址后给index函数处理
app.use('/users', usersRouter);//两个都是路由配置

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});



module.exports = app;
